package com.gitee.zw.irmp.common.config.client;

import com.gitee.zw.irmp.common.auth.sso.IrmpTokenRetriever;
import com.gitee.zw.irmp.common.config.ClientHttpHeaderInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.ReactorNettyClientRequestFactory;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;

@Slf4j
public abstract class ClientConfigCommon {


    @Autowired(required = false)
    IrmpTokenRetriever tokenRetriever;
    protected HttpServiceProxyFactory getHttpServiceProxyFactory(String apiRootUrl, String apiVersion) {

        String url = apiRootUrl;
        if (apiVersion != null && !apiVersion.isEmpty()) {
            url = apiRootUrl + "/" + apiVersion;
        }
        log.debug("url: {}, token Retrieve: {}", url, tokenRetriever);
        RestClient restClient = RestClient.builder().requestFactory(new ReactorNettyClientRequestFactory()).baseUrl(url)
                .requestInterceptor(new ClientHttpHeaderInterceptor(tokenRetriever)).build();
        RestClientAdapter adapter = RestClientAdapter.create(restClient);
        HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
        return factory;
    }
//    public CloseableHttpClient httpClient() {
//        Registry<ConnectionSocketFactory> registry =
//                RegistryBuilder.<ConnectionSocketFactory>create()
//                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
//                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
//                        .build();
//        PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager(registry);
//
//        poolingConnectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(2).build());
//        poolingConnectionManager.setDefaultConnectionConfig(ConnectionConfig.custom().build());
//
//        // set total amount of connections across all HTTP routes
//        poolingConnectionManager.setMaxTotal(200);
//        // set maximum amount of connections for each http route in pool
//        poolingConnectionManager.setDefaultMaxPerRoute(200);
//
//        RequestConfig requestConfig = RequestConfig.custom()
////                .setConnectionKeepAlive(10)
//                .setConnectionRequestTimeout(2)
////                .setResponseTimeout(2)
//                .build();
//
//        return HttpClients.custom()
//                .setDefaultRequestConfig(requestConfig)
//                .setConnectionManager(poolingConnectionManager)
//                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
//                .build();
//    }

}
